package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.kafka连接配置信息
        Properties prop = new Properties();
        //1.1设置kafka的连接地址
        prop.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.135.128:9092");
        //1.2key和value的序列化
        prop.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        prop.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        /**
         * ack  配置消息确认机制
         * 0 发送后完成不需要确认消息-速度最快
         * 1 发送给leader节点后返回成功失败响应           (默认值)
         * all 发送给leader节点--所有数据同步之后 再返回成功失败响应
         */
        prop.put(ProducerConfig.ACKS_CONFIG,"all");
        // retries  重试次数
        prop.put(ProducerConfig.RETRIES_CONFIG,10);
        //消息压缩--默认情况下 消息不会被压缩   snappy  lz4  gzip
        prop.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"snappy");


        //2.创建kafka生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(prop);
        //3.发送消息
        /**
         * 第一个参数    topic
         * 第二个参数    消息的key
         * 第三个参数    消息的value
         */
        for (int i = 0; i < 10; i++) {
            ProducerRecord<String, String> kvProducerRecord = new ProducerRecord<String,String>("zcfe-topic-input","hello Kafka");
            producer.send(kvProducerRecord);
        }


        //ProducerRecord<String, String> kvProducerRecord = new ProducerRecord<String,String>("topic-first","key-001","hello Kafka!!");
        //同步发送消息        容易产生阻塞
        // RecordMetadata recordMetadata = producer.send(kvProducerRecord).get();
        // System.out.println(recordMetadata.offset());
        //异步消息发送
        //producer.send(kvProducerRecord, new Callback() {
        //    @Override
        //    public void onCompletion(RecordMetadata recordMetadata, Exception e) {
        //        if (e!=null){
        //            System.out.println("记录异常信息到日志表中");
        //        }
        //        System.out.println(recordMetadata.offset());
        //    }
        //});
        //4.关闭消息通道---必须关闭否者消息发送不成功
        producer.close();
    }

}